import React, { Component } from "react";
import { Button, Form, Input, Checkbox, Switch, Spin, Select, Row, Col, Table, InputNumber } from "antd";
import { messages } from "share/common";
import { connect } from "react-redux";
import Priority from "components/template/priority";
import "styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss";
import NewConsumerServer from "../new-consumer-server";
import { message } from "antd/lib/index";
import ConsumerUtil from "../consumer-util";
import menuRoute from "routes/menuRoute";

const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;

@Form.create()
class FanjiaEditFrame extends Component {
  constructor(props) {
    super(props);
    this.isLock = false;
    this.applicationTypeOpts = [
      //应用类型
      { label: messages("supplier-1.key80") /*机票*/, key: "withFlightSupplier" },
      { label: messages("supplier-1.key81") /*酒店*/, key: "withHotelSupplier" },
      { label: messages("supplier-1.key82") /*火车*/, key: "withTrainSupplier" },
    ];
    this.itineraryTypeOpts = [
      //行程可选类型
      { label: messages("supplier-1.key80") /*机票*/, key: "withFlightApproval" },
      { label: messages("supplier-1.key81") /*酒店*/, key: "withHotelApproval" },
      { label: messages("supplier-1.key82") /*火车*/, key: "withTrainApproval" },
    ];
    // 暂时不做
    // this.terminalTypeOpts = [
    //   //终端可选类型
    //   { label: messages("supplier-1.key845") /*App端*/, key: "appBookButton" },
    //   { label: messages("supplier-1.key846") /*PC端*/, key: "pcBookButton" },
    // ];
    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
    };
  }

  componentWillMount() {
    console.log(this.props);
    const { params, tenant } = this.props;
    const initValue = {
      levelCode: "COMPANY",
      levelOrgName: params.distLevelOrgName,
      levelOrgId: params.levelOrgId,
    };
    if (params.companyInfos) {
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : [],
      };
    }
    this.setState(
      {
        editData: params,
        isNew: !params.levelCode,
        priDefalultValue: initValue,
      },
      this.props.form.resetFields
    );
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    });
  };

  onSubmitEdit = () => {
    if (this.isLock) {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData, costCenterDatas } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const { tenant } = this.props;
        if (!authData || !authData.levelOrgId || !authData.levelOrgName) {
          message.error(messages("supplier-1.key187") /*请填写公司*/);
          return;
        }
        const pri = {
          ...authData,
          companies: authData.distribution ? authData.distribution.companies.map((item) => item.id) : [],
        };
        delete pri.distribution;
        let upParams = Object.assign({}, values, pri);
        upParams.tenantId = tenant.id;

        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }

        this.isLock = true;
        NewConsumerServer(this)
          //这里到时候换接口
          .saveFanjia(upParams)
          .then((res) => {
            this.isLock = false;
            if (!res.data.passFlag && res.data.message) {
              message.error(res.data.message);
            } else {
              this.props.close(true);
            }
          });
      }
    });
  };

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { editData, loading, isNew, priDefalultValue } = this.state;
    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 },
    };
    return (
      <div className="edit-frame">
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages("common.column.status") /*状态*/} {...formLayout}>
              {getFieldDecorator("enabled", {
                initialValue: editData.enabled || false,
                valuePropName: "checked",
              })(<Switch onChange={this.isOpenServer} />)}
            </FormItem>
            <Priority
              top="COMPANY"
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew, valueKey: "id" }}
              defaultValue={!isNew ? priDefalultValue : null}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key194") /*服务商应用类型设置*/}</div>
            </h3>
            <FormItem
              style={{ display: "flex", alignItems: "center" }}
              label={messages("supplier-1.key195") /*应用类型*/}
              {...formLayout}
            >
              {this.applicationTypeOpts.map(({ key, label }) => {
                return (
                  <div key={key} className="edit-flex-box">
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key196") /*申请单相关设置*/}</div>
            </h3>
            <FormItem
              className="form-label-style"
              label={messages("supplier-1.key197") /*行程上可选该服务商*/}
              {...formLayout}
            >
              {this.itineraryTypeOpts.map(({ key, label }) => {
                return (
                  <div key={key} className="edit-flex-box">
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>
          </Form>
        </Spin>
        <div className="affix-bottom">
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages("common.ok") /*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

FanjiaEditFrame.getEditData = (record) => {
  const params = JSON.parse(JSON.stringify(record));
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

export default connect(mapStateToProps)(FanjiaEditFrame);
